package com.ruoyi.waterManagement.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.ruoyi.common.core.domain.business.waterManagement.WrStatvolH;
import com.ruoyi.common.core.domain.business.waterManagement.WrStatvolM;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.business.BusinessUtils;
import com.ruoyi.waterManagement.domain.vo.NzyWrStatvolMVO;
import com.ruoyi.waterManagement.domain.vo.RzsWrStatvolHwrVO;
import com.ruoyi.waterManagement.domain.vo.WaterReportVO;
import com.ruoyi.waterManagement.mapper.WrStatvolHMapper;
import com.ruoyi.waterManagement.mapper.WrStatvolMMapper;
import com.ruoyi.waterManagement.service.IWrStatvolHService;
import com.ruoyi.waterManagement.service.IWrStatvolMService;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

/**
 * 测站月水量数据Service业务层处理
 * 
 * @author hwd
 * @date 2023-02-20
 */
@Service
public class WrStatvolMServiceImpl implements IWrStatvolMService
{
    @Autowired
    private WrStatvolMMapper wrStatvolMMapper;
    @Autowired
    private WrStatvolHMapper wrStatvolHMapper;
    /**
     * 查询测站月水量数据
     * 
     * @param statCd 测站月水量数据主键
     * @return 测站月水量数据
     */
    @Override
    public WrStatvolM selectWrStatvolMByStatCd(String statCd)
    {
        return wrStatvolMMapper.selectWrStatvolMByStatCd(statCd);
    }

    /**
     * 查询测站月水量数据列表
     * 
     * @param wrStatvolM 测站月水量数据
     * @return 测站月水量数据
     */
    @Override
    public List<WrStatvolM> selectWrStatvolMList(WrStatvolM wrStatvolM)
    {
        return wrStatvolMMapper.selectWrStatvolMList(wrStatvolM);
    }

    /**
     * 新增测站月水量数据
     * 
     * @param wrStatvolM 测站月水量数据
     * @return 结果
     */
    @Override
    public int insertWrStatvolM(WrStatvolM wrStatvolM)
    {
        return wrStatvolMMapper.insertWrStatvolM(wrStatvolM);
    }

    /**
     * 修改测站月水量数据
     * 
     * @param wrStatvolM 测站月水量数据
     * @return 结果
     */
    @Override
    public int updateWrStatvolM(WrStatvolM wrStatvolM)
    {
        return wrStatvolMMapper.updateWrStatvolM(wrStatvolM);
    }

    /**
     * 批量删除测站月水量数据
     * 
     * @param statCds 需要删除的测站月水量数据主键
     * @return 结果
     */
    @Override
    public int deleteWrStatvolMByStatCds(String[] statCds)
    {
        return wrStatvolMMapper.deleteWrStatvolMByStatCds(statCds);
    }

    /**
     * 删除测站月水量数据信息
     * 
     * @param statCd 测站月水量数据主键
     * @return 结果
     */
    @Override
    public int deleteWrStatvolMByStatCd(String statCd)
    {
        return wrStatvolMMapper.deleteWrStatvolMByStatCd(statCd);
    }

    @Override
    public List<NzyWrStatvolMVO> selectNzyWrStatvolMVO(NzyWrStatvolMVO nzyWrStatvolMVO) {
        return wrStatvolMMapper.selectNzyWrStatvolMVO(nzyWrStatvolMVO);
    }

    @Override
    public List<WaterReportVO> selectMonthWaterReport(WaterReportVO waterReportVO) {
        return listMonthWaterReport(waterReportVO);
    }

    @Override
    public void exportMonthWaterReport(WaterReportVO waterReportVO, HttpServletResponse response) throws IOException {
        int yy=1970;
        int mm=1;
        int dd =1;
        if (waterReportVO.getMm()==null){
            Calendar calendar= Calendar.getInstance();
            calendar.setTime(new Date());
            yy=calendar.get(Calendar.YEAR);
            mm=calendar.get(Calendar.MONTH)+1;
        }else {
            yy=Integer.parseInt(waterReportVO.getMm().split("-")[0]);
            mm=Integer.parseInt(waterReportVO.getMm().split("-")[1]);
        }
        String excelTitle = waterReportVO.getOrgNm() +yy+"年"+mm+"月" + "水量月报";
        InputStream inputStream = null;
        List<WaterReportVO> list = null;
        WaterReportVO sumVO = null;
        inputStream = this.getClass().getClassLoader().getResourceAsStream("static/file/水量月报.xlsx");
        list = listMonthWaterReport(waterReportVO);
        List<WaterReportVO> result = new ArrayList<>();
        result.addAll(list);
        // 添加表头和日期
        Map<String, String> map = new HashMap<>();
        map.put("excelTitle", excelTitle);
        ServletOutputStream out = response.getOutputStream();
        ExcelWriter excelWriter = EasyExcel.write(out, WaterReportVO.class).withTemplate(inputStream).build();
        WriteSheet writeSheet = EasyExcel.writerSheet().build();
        excelWriter.fill(result, writeSheet);
        excelWriter.fill(map, writeSheet);
        excelWriter.finish();
    }


    public List<WaterReportVO> listMonthWaterReport (WaterReportVO monthWaterReportVO){
    /**入参水管机构 日期
     */
    //判断关键参数日期是否存在
    String wrdate=monthWaterReportVO.getMm();
    if(StringUtils.isNotEmpty(wrdate)){
        //晚于当前日期或者没有日期，则改为当前日期
    }else{
        wrdate=DateUtils.parseDateToStr(DateUtils.YYYY_MM,new Date());
    }
    wrdate= wrdate.replace("-", "");
    monthWaterReportVO.setMm(wrdate);
    if (StringUtils.isEmpty(monthWaterReportVO.getOrgCd())) {
        monthWaterReportVO.setOrgCd(null);
    }
    //找到下属的所有水管机构的统计
    HashMap<String, Object> addvAndOrgCodeInfo = BusinessUtils.getAddvAndOrgCodeInfo(monthWaterReportVO.getOrgCd());
    int grade = (int) addvAndOrgCodeInfo.get("grade");
    String resCode = (String) addvAndOrgCodeInfo.get("resCode");
    monthWaterReportVO.setOrgCd(resCode+"%");
    List<WaterReportVO> monthWaterReportList = wrStatvolMMapper.selectMonthWaterReport(monthWaterReportVO);
    if (grade == 1){
        //查找下属水管机构
        resCode =  resCode + "%0000";
    }else if (grade == 2) {
        //查找下属水管机构
        resCode =resCode + "%00";
    }else if(grade ==3) {
        resCode =resCode+"%";
    }else {
        resCode = resCode;
    }
    //查找下属机构
    RzsWrStatvolHwrVO rzsWrStatvolHwrVO=new RzsWrStatvolHwrVO();
    rzsWrStatvolHwrVO.setOrgCd(resCode);
    List<RzsWrStatvolHwrVO> orglist = wrStatvolHMapper.listOrgCd(rzsWrStatvolHwrVO);
    List<WaterReportVO> orgnewList =new ArrayList<>();
    //遍历查询下属水管机构统计
    for (RzsWrStatvolHwrVO r:orglist
    ) {
        HashMap<String, Object> stringObjectHashMap = BusinessUtils.getAddvAndOrgCodeInfo(r.getOrgCd());
        String ro = (String) stringObjectHashMap.get("resCode");
        List<WaterReportVO> monthWaterReportVOList = monthWaterReportList.stream().filter(s -> s.getOrgCd().startsWith(ro)).collect(Collectors.toList());
        WaterReportVO wrVoSum =new WaterReportVO();
        BigDecimal monWaterVol =new BigDecimal("0");
        wrVoSum.setOrgNm(r.getOrgNm());
        if (monthWaterReportVOList.size()>0) {
            for (WaterReportVO w : monthWaterReportVOList
            ) {
                monWaterVol = w.getMonVol() == null ? monWaterVol.add(new BigDecimal("0")) : monWaterVol.add(w.getMonVol()).setScale(4, BigDecimal.ROUND_HALF_UP);
            }
        }
        wrVoSum.setOrgCd("合计");
        wrVoSum.setMonVol(monWaterVol);
        orgnewList.add(0,wrVoSum);
    }
    orgnewList.removeAll(Collections.singleton(null));
    //将数据结果放入map中区分时
    Collections.reverse(orgnewList);
    return orgnewList;
}

}
